package oboe.controllers.jml.helpers.scrollBar;

import flash.display.DisplayObjectContainer;
import flash.display.Sprite;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.geom.Matrix;

import oboe.utils.CallbackHandle;

class Bar extends Sprite
{
public static inline var CSIZE:Int = 20;

public var btnFillColor1:UInt = 0x909090;
public var btnFillColor2:UInt = 0x888888;
public var barFillColor:UInt = 0x707070;
public var btnDragColor1:UInt = 0xB0B0B0;
public var btnDragColor2:UInt = 0xA0A0A0;

private var gradMat:Matrix;

private var container:DisplayObjectContainer;
public var offset:Float = 0;

private var dragCB:CallbackHandle;
private var dragCB2:CallbackHandle;

private var isHidden:Bool;
private var isSmall:Bool;

public function new( container:DisplayObjectContainer )
{
	super();
	this.container = container;
	
	this.gradMat = new Matrix();
	
	Object( container ).addCallback( "changeSize", update );
	Object( this ).addCallback( MouseEvent.MOUSE_DOWN, onStartDrag );
	
	container.addEventListener( "showBar", onShowBar );
	container.addEventListener( "hideBar", onHideBar );
	Object( container ).addCallbackEx( "onScroll", onScroll ); 
	
	isHidden = true;
	isSmall = false;
	
	this.update();
}

private function onShowBar( e:BarEvent ):Void
{
	if( e.bar == this || this.isSmall ) return;
	this.isSmall = true;
	this.update();
}

private function onHideBar( e:Event ):Void
{
	if( e.currentTarget == this || !this.isSmall ) return;
	this.isSmall = false;
	this.update();
}


private function onStartDrag():Void
{
	if( this.dragCB ) Object( this ).removeCallback( this.dragCB );
	this.dragCB = Object( this.stage ).addCallbackEx( MouseEvent.MOUSE_MOVE, onPreDrag );
	this.dragCB2 = Object( this.stage ).addCallback( MouseEvent.MOUSE_UP, onStopDrag );

	this.onDrag();
	this.emit("onScroll");
}

private function emit(e:String, sendThis:Bool=true ):Void
{
	this.container.dispatchEvent( new BarEvent(e, sendThis?this:null ) );
}

private function onScroll( e:BarEvent ):Void
{
	this.update( e.bar == this );
}

private function onPreDrag( e:MouseEvent ):Void
{
	if( !e.buttonDown )
	{
	this.onStopDrag();
	}
	else
	{
	this.onDrag();
	this.emit("onScroll");
	}
}

private function onStopDrag():Void
{
	if( this.dragCB ) Object( this.stage ).removeCallback( this.dragCB );
	if( this.dragCB2 ) Object( this.stage ).removeCallback( this.dragCB2 );
	this.emit("onScroll", false);
}

private function onDrag():Void{}

public function update( dragging:Bool=false ):Void{} // override me

}